using CollabApp.Infrastructure;
using CollabApp.Application;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using CollabApp.Application.DTOs;
using System.Text;

namespace CollabApp.API;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // ====================================
        // 注册应用服务
        // ====================================
        RegisterApplicationServices(builder);

        // 移除Session相关注册
        // builder.Services.AddDistributedMemoryCache();
        // builder.Services.AddSession();

        // ====================================
        // 添加 CORS 服务
        // ====================================
        builder.Services.AddCors(options =>
        {
            options.AddPolicy("AllowFrontend",
                policy => policy
                    .WithOrigins("http://localhost:5173", "https://localhost:5173")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials());
        });

        // ====================================
        // 配置数据库连接
        // ====================================
        ConfigureDatabase(builder);

        var app = builder.Build();

        // ====================================
        // 数据库初始化
        // ====================================
        InitializeDatabase(app);

        // ====================================
        // 配置中间件管道
        // ====================================
        ConfigurePipeline(app);

        // 移除Session中间件
        // app.UseSession();

        app.Run();
    }

    // 注册应用服务
    private static void RegisterApplicationServices(WebApplicationBuilder builder)
    {
        // Add services to the container.
        // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
        builder.Services.AddOpenApi();

        // 注册基础设施层服务
        builder.Services.AddInfrastructure(builder.Configuration);

        // ====================================
        // 添加 SignalR 服务
        // ====================================
        builder.Services.AddSignalR(options =>
        {
            // 配置SignalR选项
            options.EnableDetailedErrors = builder.Environment.IsDevelopment();
            options.KeepAliveInterval = TimeSpan.FromSeconds(15);
            options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
            options.HandshakeTimeout = TimeSpan.FromSeconds(15);
        }).AddJsonProtocol(options =>
        {
            // 配置JSON序列化选项
            options.PayloadSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
        });

        // ====================================
        // 添加控制器支持
        // ====================================
        builder.Services.AddControllers()
            .AddJsonOptions(options =>
            {
                // 配置JSON序列化选项
                options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.WriteIndented = builder.Environment.IsDevelopment();
            });

        // ====================================
        // 添加身份验证支持（JWT）
        // ====================================
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var jwtSection = builder.Configuration.GetSection("Jwt");
                var jwtSettings = jwtSection.Get<JwtSettings>() ?? new JwtSettings();
                
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtSettings.Issuer ?? string.Empty,
                    ValidAudience = jwtSettings.Audience ?? string.Empty,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey ?? "default-secret-key-for-development-only-please-change-in-production"))
                };

                // 添加SignalR事件处理
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path = context.HttpContext.Request.Path;
                        
                        // 如果请求来自SignalR Hub，从查询字符串中获取token
                        if (!string.IsNullOrEmpty(accessToken) && 
                            (path.StartsWithSegments("/gameHub") || path.StartsWithSegments("/lineDrawingGameHub")))
                        {
                            context.Token = accessToken;
                        }
                        
                        return Task.CompletedTask;
                    }
                };
            });

        // 注册应用层服务
        builder.Services.AddApplication(builder.Configuration);

        // ====================================
        // 注册后台服务：每日00:00同步排行榜到PG
        // ====================================
        builder.Services.AddHostedService<CollabApp.API.HostedServices.RankingSyncHostedService>();

    }

    // 配置中间件管道
    private static void ConfigurePipeline(WebApplication app)
    {
        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.MapOpenApi();
        }

        // 启用 CORS
        app.UseCors("AllowFrontend");

        // ====================================
        // 启用身份验证和授权
        // ====================================
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseHttpsRedirection();

        // ====================================
        // 映射控制器路由
        // ====================================
        app.MapControllers();

        // ====================================
        // 映射 SignalR Hubs
        // ====================================
        app.MapHub<CollabApp.API.Hubs.GameHub>("/gameHub");
        app.MapHub<CollabApp.API.Hubs.LineDrawingGameHub>("/lineDrawingGameHub");

        // ====================================
        // 测试端点（可删除）
        // ====================================
        var summaries = new[]
        {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };

        app.MapGet("/weatherforecast", () =>
        {
            var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                (
                    DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    Random.Shared.Next(-20, 55),
                    summaries[Random.Shared.Next(summaries.Length)]
                ))
                .ToArray();
            return forecast;
        })
        .WithName("GetWeatherForecast");
    }

    // 配置数据库连接
    private static void ConfigureDatabase(WebApplicationBuilder builder)
    {
        var postgresConfig = builder.Configuration.GetConnectionString("Postgres");
        var redisConfig = builder.Configuration.GetConnectionString("Redis");
        // 这里可以添加数据库上下文的配置代码


    }
    // 天气预报模型
    private record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
    {
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
     private static void InitializeDatabase(WebApplication app)
    {
        // 立即初始化数据库并添加系统数据
        using var scope = app.Services.CreateScope();
        try
        {
            // 使用新的数据库初始化服务
        }
        catch (Exception ex)
        {
            // 处理数据库初始化异常
            var logger = scope.ServiceProvider.GetService<ILogger<Program>>();
            logger?.LogError(ex, "数据库初始化失败");
        }
    }
}

